package main

import (
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
)

const (
	DingURL = "https://oapi.dingtalk.com/robot/send?access_token="
)

// Dingding 调用钉钉机器人
func Dingding(msg string) {
	msg = CheckMessage(msg)
//注意，此处从文件读取时会有一个回车换行符(\n)，需要去除
	token := GetToken()
	webhook := DingURL + token[:len(token)-1]
	content := `{"msgtype": "text",
		"text": {"content": "` + msg + `"}
	}`
	req, err := http.NewRequest("POST", webhook, strings.NewReader(content))
	if err != nil {
		log.Println(err)
		return
	}
	client := &http.Client{}
	req.Header.Set("Content-Type", "application/json; charset=utf-8")
	resp, err := client.Do(req)
	log.Print("HTTP状态响应码：", resp.StatusCode)
	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	log.Println(string(body))
	if err != nil {
		log.Println(err)
	}

}

// CheckMessage 替换转义字符，确保“\”可以正常输出
func CheckMessage(msg string) string {
	return strings.Replace(msg, "\"", "\\\"", -1)
}

func GetToken() string {
	configPath := os.Getenv("HOME") + string(os.PathSeparator) + "ding_token"
	file, err := os.Open(configPath)
	defer file.Close()
	if err != nil {
		log.Println(err)
		return ""
	}
	//初始化字节数组100，实际钉钉token是64，主要是体现读取的返回值
	b := make([]byte, 100)
	n, err := file.Read(b)
	if err != nil {
		log.Println(err)
		return ""
	}
	key := string(b[:n])
	log.Println(key)
	return key

}

func main() {

	n := len(os.Args)
	switch n {
	case 1:
		log.Println("没有参数，自动退出。。。")
		log.Println("Usage:    ding 'message'")
	case 2:
		Dingding(os.Args[1])
	default:
		log.Println("参数错误，自动退出。。。")
		log.Println("Usage:    ding 'message'")
	}

}
